package com.opdar.athena.support.controllers.support;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.opdar.athena.support.base.CommonInterceptor;
import com.opdar.athena.support.base.Constants;
import com.opdar.athena.support.base.ICacheManager;
import com.opdar.athena.support.base.Result;
import com.opdar.athena.support.entities.SupportConfigEntity;
import com.opdar.athena.support.entities.SupportUserEntity;
import com.opdar.athena.support.mapper.SupportConfigMapper;
import com.opdar.athena.support.service.SupportUserService;
import com.opdar.platform.annotations.Interceptor;
import com.opdar.platform.annotations.Request;
import com.opdar.platform.core.base.Context;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import java.util.List;

/**
 * Created by shiju on 2017/7/13.
 */
@Controller
@Interceptor(CommonInterceptor.class)
public class WorkmateController {

    @Autowired
    SupportUserService userService;
    @Autowired
    SupportConfigMapper supportConfigMapper;
    @Autowired
    ICacheManager<String, String, Object> cacheManager;


    @Request(value = "/workmate/list", format = Request.Format.JSON)
    public Result supportWorkmateList() {
        SupportUserEntity user = (SupportUserEntity) Context.getRequest().getAttribute("user");
        List<SupportUserEntity> list = userService.findAllSupport(user.getAppId());
        JSONArray result = new JSONArray();
        for(SupportUserEntity supportUserEntity:list){
            if(supportUserEntity.getId().equals(user.getId())){
                //自己 跳过
                continue;
            }
            String token = (String) cacheManager.hget(Constants.LAST_TOKEN,supportUserEntity.getId());
            if(token != null){
                Integer userState = (Integer) cacheManager.hget(Constants.USER_STATE,supportUserEntity.getId());
                SupportConfigEntity config = new SupportConfigEntity();
                config.setName(Constants.AUTO_TRANSFER);
                config.setSupportId(supportUserEntity.getId());
                config = supportConfigMapper.selectOne(config);
                if(config != null && config.getStat() == 1){
                    if(userState == 0 || userState == 1){
                        JSONObject object = new JSONObject();
                        object.put("userState",userState);
                        object.put("user",supportUserEntity);
                        result.add(object);
                    }
                }
            }
        }
        return Result.valueOf(result);
    }

}
